package com.dandelion.framework.exceptions;

import com.dandelion.framework.enums.CodeEnum;
import com.dandelion.framework.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


import java.util.List;
import java.util.stream.Collectors;

/**
 * 全球异常处理器
 *
 * @author 77088
 * @date 2022/02/16
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionProcessor {


    @ExceptionHandler(value = ServerException.class)
    public R serverExceptionHandler(ServerException ex) {
        return R.fail(ex.getCode(), ex.getMsg());
    }



    /**
     * 拦截表单参数校验
     */
    @ExceptionHandler({BindException.class})
    public R bindException(BindException ex) {
        // 获取所有异常
        List<String> errors = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(x -> x.getDefaultMessage())
                .collect(Collectors.toList());
        return R.fail(CodeEnum.PARAM_ERROR.getCode(), CodeEnum.PARAM_ERROR.getMsg() + ":" + String.join(",", errors));

    }
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleBindGetException(MethodArgumentNotValidException ex) {
        // 获取所有异常
        List<String> errors = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(x -> x.getDefaultMessage())
                .collect(Collectors.toList());
        return R.fail(CodeEnum.PARAM_ERROR.getCode(), CodeEnum.PARAM_ERROR.getMsg() + ":" + String.join(",", errors));
    }


}
